package com.sinopec.scandevice.view

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Paint
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.text.Editable
import android.text.InputFilter.LengthFilter
import android.text.InputType
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.widget.CompoundButton
import androidx.core.app.NotificationManagerCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.gyf.immersionbar.ImmersionBar
import com.jakewharton.rxbinding3.view.clicks
import com.jakewharton.rxbinding3.view.longClicks
import com.jakewharton.rxbinding3.widget.textChanges
import com.tbruyelle.rxpermissions2.RxPermissions
import com.sinopec.basemodule.AppConstants
import com.sinopec.basemodule.BaseApplication
import com.sinopec.basemodule.base.BaseActivity
import com.sinopec.basemodule.base.CustomToolbar
import com.sinopec.basemodule.common.CommonVebViewActivity
import com.sinopec.basemodule.common.Logger
import com.sinopec.basemodule.model.login_model.UserInfo
import com.sinopec.basemodule.router.ReflectUtils
import com.sinopec.basemodule.utils.ARouterManagerUtils
import com.sinopec.basemodule.utils.PhoneUtils
import com.sinopec.basemodule.utils.StringUtils
import com.sinopec.basemodule.utils.ToastUtils
import com.sinopec.ch34x.device.core.config.Config
import com.sinopec.ch34x.device.core.init.initUsbDriver
import com.sinopec.scandevice.BuildConfig
import com.sinopec.scandevice.MyApp
import com.sinopec.scandevice.R
import com.sinopec.scandevice.contract.LoginContract
import com.sinopec.scandevice.inputFilter.ChineseInputFilter
import com.sinopec.scandevice.presenter.LoginPresenter
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.BiFunction
import kotlinx.android.synthetic.main.activity_login.*
import java.util.concurrent.TimeUnit

/**
 * @author lwj
 * @ClassName: LoginActivity
 * @Description: 登录页面
 */
@Route(path = ARouterManagerUtils.GOTO_LM_LOGIN_ACTIVITY)
open class LoginActivity : BaseActivity<LoginPresenter?>(), LoginContract.View {
    private val TAG = "LoginActivity"

    override fun getContentView(): Int {
        return R.layout.activity_login
    }

    override fun configToolbar(rToolbar: CustomToolbar) {
        rToolbar.setToolbarVisible(false)
    }

    override fun setStatusBar() {
        super.setStatusBar()
        ImmersionBar.with(this).statusBarDarkFont(true).init()
    }

    override fun initView(savedInstanceState: Bundle?) {
        // 通知权限没有打开，打开设置通知界面
        //checkNotificationPermission()
        //检查更新
//        Beta.checkUpgrade(false, false)
        BaseApplication.getInstance().appUpdateEvent(false)

        initUsbDriver(this, Config())

        //账号编辑
        et_username.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
                Logger.i(TAG, "s=$s starit=$start count=$count after=$after")
            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                Logger.i(TAG, "s=$s start=$start before=$before count=$count")
                if (s.isNotEmpty()) {
                    iv_clear.visibility = View.VISIBLE
                } else {
                    iv_clear.visibility = View.GONE
                }
            }

            override fun afterTextChanged(s: Editable) {
                Logger.i(TAG, "s=$s")
            }
        })
        //密码清除按钮
        et_pwd.filters = arrayOf(
            LengthFilter(16), ChineseInputFilter()
        )
        et_pwd.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
                Logger.i(TAG, "s=$s start=$start count=$count after=$after")
            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                Logger.i(TAG, "s=$s start=$start before=$before count=$count")
                if (s.isNotEmpty()) {
                    iv_clear_password.visibility = View.VISIBLE
                } else {
                    iv_clear_password.visibility = View.GONE
                }
            }

            override fun afterTextChanged(s: Editable) {
                Logger.i(TAG, "s=$s")
            }
        })
        //密码显示
        cb_hide_password.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
            Logger.d(TAG, "onCheckedChanged: $isChecked")
            if (isChecked) {
                //选择状态 显示明文--设置为可见的密码
                et_pwd.inputType = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
                et_pwd.setSelection(et_pwd.length())
            } else {
                //默认状态显示密码--设置文本 要一起写才能起作用 InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD
                et_pwd.inputType =
                    InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
                et_pwd.setSelection(et_pwd.length())
            }
        })

        val userNameObservable = et_username.textChanges()
            .map { obj: CharSequence -> obj.toString() }
            .map { driverPhone: String? -> !driverPhone.isNullOrEmpty() }
        val pwdObservable = et_pwd.textChanges()
            .map { obj: CharSequence -> obj.toString() }
            .map { msgCode: String? -> StringUtils.checkPwd(msgCode) }
        addDisposable(Observable
            .combineLatest(userNameObservable,
                pwdObservable,
                BiFunction { nameIsAvailable: Boolean, pwdIsAvailable: Boolean -> nameIsAvailable && pwdIsAvailable })
            .subscribe { enable: Boolean? -> tv_login.isEnabled = enable!! })

        //有用户信息就进入主界面
        if (MyApp.getInstance().userManager.user != null
            && MyApp.getInstance().token != null
        ) {
            ReflectUtils.navigationToHome(mContext, 0)
            mContext.finish()
        }

        tv_version_name.text = BaseApplication.getInstance().versionName
        tv_icp.paintFlags = tv_icp.paintFlags or Paint.UNDERLINE_TEXT_FLAG
        //获取设备号
        refreshDeviceId()
    }

    override fun initData() {
        super.initData()
        mPresenter = LoginPresenter(this)
    }

    /**
     * 设置事件监听
     */
    @SuppressLint("ClickableViewAccessibility")
    override fun initEvent() {
        super.initEvent()

        /**
         * 检查更新
         */
        addDisposable(ll_version.clicks()
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                //检查更新
                BaseApplication.getInstance().appUpdateEvent(true)
            })

        /**
         * 跳转备案号界面
         */
        addDisposable(tv_icp.clicks()
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                CommonVebViewActivity.startActivity(
                    mContext,
                    AppConstants.ICP_URL,
                    "ICP/IP地址/域名信息备案管理系统"
                )
            })

        /**
         * 环境切换
         */
        addDisposable(ll_device!!.longClicks()
            .throttleFirst(1, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                if (BuildConfig.DEBUG) {
                    navigationTo(DebugActivity::class.java)
                }
            })


        /**
         * 登录按钮
         */
        addDisposable(tv_login!!.clicks()
            .throttleFirst(1, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe { login() })

        /**
         * 清空账号
         */
        addDisposable(iv_clear!!.clicks()
            .subscribe { et_username!!.setText("") })


        /**
         * 清空密码
         */
        addDisposable(iv_clear_password!!.clicks()
            .subscribe { et_pwd!!.setText("") })
    }

    /**
     * 点击登录
     */
    private fun login() {
        //登录用户名（手机号码）密码、验证码
        var userPhone = et_username!!.text.toString()
        if (!TextUtils.isEmpty(userPhone) && userPhone.contains("-")) {
            userPhone = userPhone.replace("-", "")
        }
        val passwordOrCode = et_pwd!!.text.toString()
        val deviceId = tv_device_id!!.text.toString()
        if (!TextUtils.isEmpty(deviceId)) {
            //网络请求登录
            //mPresenter!!.login(userPhone, passwordOrCode, deviceId)

            //模拟登录成功流程
            val token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyblN0ciI6IlNGMHBFUWp6MWRYc0swNkY0dExsd3NRbFN5cXhkUUVDIn0.VEq1Y_ZPeBeTR412szW2zjwFmcmdu4t8BJMz1YAtNHE"
            BaseApplication.getInstance().updateToken(token)
            val userInfo = UserInfo()
            userInfo.deviceId = deviceId
            userInfo.userId = ""
            userInfo.userName = ""
            userInfo.userAccount = userPhone
            BaseApplication.getInstance().userManager.user = userInfo
            ReflectUtils.navigationToHome(mContext, 0)
            mContext.showMessage("登录成功")
            mContext.finish()
        } else {
            refreshDeviceId()
        }
    }

    private fun checkNotificationPermission() {
        if (!NotificationManagerCompat.from(this).areNotificationsEnabled()) {
            showMessage("请打开应用的通知权限，以方便接收到通知消息")
            val intent = Intent()
            intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
            val uri = Uri.fromParts("package", packageName, null)
            intent.data = uri
            startActivity(intent)
        }
    }

    /**
     * 获取设备号
     */
    private fun refreshDeviceId() {
        addDisposable(RxPermissions(this@LoginActivity)
            .request(Manifest.permission.READ_PHONE_STATE)
            .subscribe { aBoolean ->
                if (aBoolean) {
                    @SuppressLint("MissingPermission") val deviceId = PhoneUtils.getDeviceId()
                    tv_device_id_label!!.text = "设备ID："
                    tv_device_id!!.text = deviceId
                    Log.i(TAG, "设备ID：" + deviceId)
                } else {
                    ToastUtils.showToast("请允许获取手机读取权限！")
                }
            })
    }

    /**
     * 登录失败
     */
    override fun loginError(msg: String?) {
        if (!TextUtils.isEmpty(msg)) {
            tv_error.text = msg
            ll_error.visibility = View.VISIBLE
        } else {
            ll_error.visibility = View.GONE
        }
    }
}